#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author:Charmander

import glob
import os
import smtplib
import threading
import zipfile
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from Advisement_player import readConfig as readConfig
from Advisement_player.common.log import MyLog

localReadConfig = readConfig.ReadConfig()

class Email:
    def __init__(self):
        global host,port,sender,password,title
        host = localReadConfig.get_email('mail_host')
        port = localReadConfig.get_email('mail_port')
        sender = localReadConfig.get_email('mail_user')
        password = localReadConfig.get_email('mail_pass')
        subject = localReadConfig.get_email('title')
        self.member = localReadConfig.get_email('receiver')
        self.receivers = []
        for m in self.member.split(';'):        #添加收件人，并用‘；’区分开
            self.receivers.append(m)

        data = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.title = subject + data         #邮件标题

        self.log = MyLog.get_log()
        self.logger = self.log.get_logger()
        self.msg = MIMEMultipart('related')     #内嵌方式吧HTML附带在邮件中

    #邮件头
    def config_header(self):
        self.msg['subject'] = self.title       #邮件主题
        self.msg['from'] = sender       #邮件发件人
        self.msg['to'] = ';'.join(self.receivers)       #邮件收件人

    #编写邮件内容
    def config_content(self):
        f = open(os.path.join(readConfig.proDir, 'testFile', 'email.txt'))
        content = f.read()
        f.close()
        content_plain = MIMEText(content,'html','UTF-8')        #创建HTML邮件内容
        self.msg.attach(content_plain)      #添加邮件内容

    def config_file(self):
        '''
        files:返回日期里的所有文件
        zippath：result文件夹路径
        reportpath：result里日期的文件夹路径
        '''
        reportpath = self.log.get_result_path()
        zippath = os.path.join(readConfig.proDir, 'result', 'test.zip')       #在result下，创建一个压缩文件目录

        files = glob.glob(reportpath + '\*')
        f = zipfile.ZipFile(zippath,mode='w',compression=zipfile.ZIP_DEFLATED)        #创建一个压缩对象
        for file in files:
            f.write(file, '/report/'+os.path.basename(file))       #修改压缩文件目录结构
        f.close()

        reportfile = open(zippath,'rb').read()
        filezip =MIMEText(reportfile,'base64','UTF-8')
        filezip['Content-Type'] = 'application/octet-stream'
        filezip['Content-Disposition'] = 'attachment; filename="test.zip"'
        self.msg.attach(filezip)

    def send_email(self):
        self.config_header()
        self.config_content()
        self.config_file()
        try:
            smtpObj = smtplib.SMTP_SSL(host,port)
            #smtpObj.connect('smtp.exmail.qq.com','465')        #连接邮箱服务器，端口默认25
            #smtpObj.ehlo()
            #smtpObj.starttls()
            #smtpObj.starttls()      #启动安全传输模式
            smtpObj.login(sender,password)        #登录邮箱服务器
            smtpObj.sendmail(sender, self.receivers, self.msg.as_string())      #发送邮件
            smtpObj.quit()      #关闭smtp服务器连接
            print('邮件发送成功')
            self.logger.info('Report has send succeed !')
        except Exception as ex:
            self.logger.error(str(ex))

class TestEmail:
    email = None
    mutex = threading.Lock()

    def __init__(self):
        pass

    @staticmethod
    def get_email():
        if TestEmail.email is None:
            TestEmail.mutex.acquire()
            TestEmail.email = Email()
            TestEmail.mutex.release()
        return TestEmail.email


if __name__ == '__main__':
    email = TestEmail.get_email()